import os
import sys
import logging
from logging.handlers import RotatingFileHandler

class Log(object):
    def __init__(self, path=None):
        if os.path.exists(path):
            curdir = path
        else:
            curdir = os.getcwd()

        self._logdir = os.path.join(curdir, "log")
        print("current directory: " + self._logdir)

        if not os.path.exists(self._logdir):
            print("creating log dir")
            os.mkdir(self._logdir)

        first_log = os.path.join(self._logdir, "log.txt")

        self._logger = logging.getLogger(__name__)
        self._logger.setLevel(logging.INFO)

        rHandler = RotatingFileHandler(first_log, maxBytes = 100*1024, backupCount = 10)
        rHandler.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        rHandler.setFormatter(formatter)

        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(formatter)

        self._logger.addHandler(rHandler)
        self._logger.addHandler(console)
        self._handler_list = [rHandler, console]

    def close(self):
        self._logger.shutdown(self._handler_list)

    def D(self, log=None):
        self._logger.debug(log)

    def I(self, log=None):
        self._logger.info(log)

    def W(self, log=None):
        self._logger.warning(log)

    def E(self, log=None):
        self._logger.error(log)

    def F(self, log=None):
        self._logger.fatal(log)

